﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using BitwiseOre.Properties;

namespace BitwiseOre.SharedMemory.Utils
{
    internal static class ExceptionExtentions
    {
        private static readonly string TimedoutMessage = Resources.ExceptionExtentions_TimedoutMessage;

        public static Exception Wrap(this AggregateException exception,
                                     Func<AggregateException, Exception> createException)
        {
            var exceptions = exception.InnerExceptions.Descendants(
                e => e is AggregateException
                         ? ((AggregateException) e).InnerExceptions
                         : Enumerable.Empty<Exception>());

            return exceptions.OfType<TimeoutException>().Any()
                       ? new TimeoutException(TimedoutMessage, exception)
                       : createException(exception);
        }

        private static IEnumerable<T> Descendants<T>(this IEnumerable<T> source,
                                                Func<T, IEnumerable<T>> descendBy)
        {
            foreach (var value in source)
            {
                yield return value;

                foreach (var child in descendBy(value).Descendants<T>(descendBy))
                {
                    yield return child;
                }
            }
        }

    }
}